package com.meihua.baoleyi.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.bean.AddressListBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.pickerviewlibrary.CityPickerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 添加新地址activity
 * <p>
 * Created by liming on 2017/10/17
 * 添加新地址/修改地址
 */

public class AddAdressActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.text_title)
    TextView textTitle;
    @Bind(R.id.add_address_consignee)
    EditText addAddressConsignee;
    @Bind(R.id.add_address_phone)
    EditText addAddressPhone;
    @Bind(R.id.et_detail_address)
    EditText etDetailAddress;
    @Bind(R.id.top_right_tv)
    TextView topRightTv;
    @Bind(R.id.add_address_region)
    TextView address;
    @Bind(R.id.tv_delete)
    TextView tvDelete;
    private CityPickerView mCityPickerView;
    private AddressListBean.DatasBean mDatasBean;
    private boolean typeAddress = false; // false是添加地址 true是修改地址
    private String id; //修改地址的id
    private String province; //省
    private String city; //城市
    private String area; //地区

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ButterKnife.bind(this);
        textTitle.setText("新增地址");
        topRightTv.setText("保存");
        topRightTv.setVisibility(View.VISIBLE);
        initEditData(getIntent()); //修改地址
        mCityPickerView = new CityPickerView(this);
    }

    @OnClick({R.id.text_back, R.id.top_right_tv, R.id.add_adress_select_region_ll,R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_delete: //删除地址
                deleteAddress();
                break;
            case R.id.text_back: //返回
                finish();
                break;
            case R.id.top_right_tv: //保存
                saveAddress();
                break;
            case R.id.add_adress_select_region_ll:
                hiddenInputMethod();
                CityPickerView mCityPickerView = new CityPickerView(this);
                mCityPickerView.setOnCitySelectMoreListener(new CityPickerView.OnCitySelectMoreListener() {
                    @Override
                    public void onCitySelectMore(String one, String two, String three, String str) {
                        province = one;
                        city = two;
                        area = three;
                        address.setText(str);
                    }
                });
                mCityPickerView.show();
                break;
        }
    }
    /**
     * 如果是修改地址的话 进行初始化
     * @param intent
     */
    private void initEditData(Intent intent) {
        if(intent != null) {
            mDatasBean = (AddressListBean.DatasBean) getIntent().getSerializableExtra("addressbean");
            if(mDatasBean!=null){
                typeAddress = true;
                id = mDatasBean.getId() +"";
                textTitle.setText("修改地址");
                tvDelete.setVisibility(View.VISIBLE);
                addAddressConsignee.setText(mDatasBean.getConsignee());
                addAddressPhone.setText(mDatasBean.getPhone());
                address.setText(mDatasBean.getProvince()+mDatasBean.getCity()+mDatasBean.getArea());
                etDetailAddress.setText(mDatasBean.getAddress());
                province = mDatasBean.getProvince();
                city = mDatasBean.getCity();
                area = mDatasBean.getArea();
            }
        }
    }

    /*删除地址*/
    private void deleteAddress() {
        showDialog();
        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("id", mDatasBean.getId() + "");//地址记录id
        NetHelper.get(APIServer.ADDRESSDEL, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                JSONObject object = null;
                try {
                    object = new JSONObject(s);
                    if (object.getString("code").equals("200")) {
                        //请求成功
                        Toast.makeText(AddAdressActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(AddAdressActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
                dismissDialog();
            }
        });
    }

    /*保存地址*/
    private void saveAddress() {
        //验证信息是否完整
        if(TextUtils.isEmpty(addAddressConsignee.getText().toString())|| TextUtils.isEmpty(addAddressPhone.getText().toString())||
                TextUtils.isEmpty(etDetailAddress.getText().toString())|| TextUtils.isEmpty(address.getText().toString())){
            ToastUtil.show(this, "请填写完整信息");
        }
        if (typeAddress) { //修改地址
            editAddress();
        } else { //添加新地址
            addAddress();
        }
    }

    /**
     * 请求 添加新地址
     */
    private void addAddress() {
        showDialog();
        NetHelper.post(APIServer.ADDADDRESS, getTreeMap(), true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                JSONObject object = null;
                try {
                    object = new JSONObject(s);
                    if (object.getString("code").equals("200")) {
                        //请求成功
                        Toast.makeText(AddAdressActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    }else {
                        Toast.makeText(AddAdressActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(AddAdressActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
                dismissDialog();
            }
        });
    }

    /**
     * 请求 修改地址
     */
    private void editAddress() {
        showDialog();
        NetHelper.post(APIServer.EDIT_ADDRESS, getTreeMap(), true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                JSONObject object = null;
                try {
                    object = new JSONObject(s);
                    if (object.getString("code").equals("200")) {
                        //请求成功
                        Toast.makeText(AddAdressActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    }else {
                        Toast.makeText(AddAdressActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(AddAdressActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
                dismissDialog();
            }
        });
    }

    /**
     * 获取请求携带数据
     */
    private TreeMap<String, String> getTreeMap() {
        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        //修改地址需添加id
        if (typeAddress) {
            treeMap.put("id", id);
        }
        treeMap.put("user_id", MyApp.getInstance().getUser_id());//用户id
        treeMap.put("consignee", addAddressConsignee.getText().toString());//收货人
        treeMap.put("phone", addAddressPhone.getText().toString());//手机号
        treeMap.put("province", province);//省份
        treeMap.put("city", city);//市
        treeMap.put("area", area);//区
        treeMap.put("address", etDetailAddress.getText().toString());//地址
        return treeMap;
    }

}
